/*
 * 手工发放优惠券管理
 * @date 2016/4/27
 */

// 页面初始化
window.onload = function () {
    getType($('#type'), 1);
    list();
};

//是否请求完成标识
var loadBool = true;

//列表每页显示条数
var perPage = 10;

// 清空查询条件
$('#empty').click(function () {
    $("#starttime").val("");
    $("#endtime").val("");
    $("#phone").val("");
    $("#type").val("-1");
    $("#opuser").val("");
    $("#cmanualres").empty();
    list();
});

// 查询发放记录
$('#query').click(function () {
    list();
});

function list() {
    $("#curPage").text(0);
    $("#pages").text(0);
    getRecord(1);
}

//下一页
$(document).delegate("#nextPage", "click", function () {
    var curPage = Number($("#curPage").text());
    var pages = Number($("#pages").text());
    if (curPage == pages) {
        return;
    }
    getRecord(curPage + 1);
});

//上一页
$(document).delegate("#lastPage", "click", function () {
    var curPage = Number($("#curPage").text());
    if (curPage <= 1) {
        return;
    }
    getRecord(curPage - 1);
});

// 返回上一页
function back(elem) {
    elem.on('click', "#back", function () {
        is_incity = -1;
        layer.closeAll();
    });
}

// 标记业务分类
function bussinessMark(elem) {
    elem.on('click', "input[type='checkbox']", function () {
        var bussiness = '';
        if (elem.find("#city").prop("checked")) {
            if (elem.find("#busAll").prop("checked") || elem.find("#incipin").prop("checked") || elem.find("#incibao").prop("checked") || elem.find("#package").prop("checked")) {
                is_incity = -1;//城际和市内
            } else {
                is_incity = 1;//市内
                bussiness = '市内';
            }
        } else {
            is_incity = 0;//城际
            bussiness = '城际';
        }
        if (is_incity != -1) {
            elem.find('.route-part-control .line-model').each(function () {
                var start = $(this).find('input:first-child').val();
                if (start.indexOf(bussiness) == -1) {
                    $(this).find('input:first-child').val('');
                    $(this).find('input:nth-child(2)').val('');
                }
            });
        }
    });
}

// 获取分类id和描述
function getType(elem, is_all) {
    var param = JSON.stringify({"": ""});
    elem.empty();
    if (is_all) {//是否存在'全部'选项
        elem.append("<option value='-1'>全部</option>");
    }

    $.ajax({
        type: "POST",
        url: "/couponmanual/gtype",
        contentType: "application/json",
        dataType: "json",
        data: param,
        success: function (res) {
            if (res["status"]) {
                if (res.status == -501) {//session过期
                    window.location.href = '/timeout/index';
                } else {
                    bbx_alert_error(res.message);
                }
                return;
            }
            for (var i in res["data"]) {
                option = $("<option>").val(res["data"][i]["id"]).text(res["data"][i]["description"]);
                elem.append(option);
            }

        },
        error: function () {
            bbx_alert_error('出错啦~');
        }
    });
}

/*
 * 获取发放记录
 * @date 2016/4/27
 */
function getRecord(curPage) {
    if (!loadBool) {
        return;
    }
    loadBool = false;
    $("#cmanualres").empty();
    //loading层
    var layerIndex = layer.load(2, {
        shade: [0.1, '#fff'] //0.1透明度的白色背景
    });

    var index = curPage - 1;
    var starttime = $("#starttime").val();
    var endtime = $("#endtime").val();
    var type = Number($("#type").val());
    var phone = $("#phone").val();
    var opuser = $("#opuser").val();
    var param = JSON.stringify({"starttime": starttime, "endtime": endtime, "type": type, "phone": phone, "opname": opuser, "pos": index * perPage, "limit": perPage});
    $.ajax({
        type: "POST",
        url: "/couponmanual/grecord",
        contentType: "application/json",
        dataType: "json",
        data: param,
        success: function (res) {
            layer.close(layerIndex);
            if (res["status"]) {
                if (res.status == -501) {//session过期
                    window.location.href = '/timeout/index';
                } else {
                    bbx_alert_error(res.message);
                }
                loadBool = true;
                return;
            }
            $("#pages").text(Math.ceil(res.count / perPage));

            if (res.data.length > 0) {
                $("#curPage").text(index + 1);
                for (var i in res["data"]) {
                    var phone_col = "";
                    for (var j in res["data"][i]["phone"]) {
                        phone_col += "<p>" + res["data"][i]["phone"][j] + ";</p>";
//                        phone_col += res["data"][i]["phone"][j] + ";";
                    }
                    var row = "<tr>\
                            <td id='id' style='display:none'>" + res["data"][i]["id"] + "</td>\
                            <td id='opuid' style='display:none'>" + res["data"][i]["opuid"] + "</td>\
                            <td>" + res["data"][i]["create_time"] + "</td>\
                            <td>" + phone_col + "</td>\
                            <td>" + res["data"][i]["cnt"] + "</td>\
                            <td>" + res["data"][i]["typedesc"] + "</td>";

                    if (res["data"][i]["sendmsg"] == "是") {
                        row += "<td class='message' tit=" + res["data"][i]["msg"] + ">" + res["data"][i]["sendmsg"] + "</td>";
                    } else {
                        row += "<td>" + res["data"][i]["sendmsg"] + "</td>";
                    }
                    row += "<td>" + res["data"][i]["remark"] + "</td>\
                        <td><a class='details' href='javascript:void(0);' title=\"\">详情</a>\
                        </tr>";
                    $("#cmanualres").append(row);
                }
            }
            loadBool = true;
        },
        error: function () {
            layer.close(layerIndex);
            bbx_alert_error('出错啦~');
            loadBool = true;
        }
    });
}

/*
 * 查看短信内容
 * @date 2016/4/27
 */
$('.table').delegate('td.message', 'click', function () {
    var tit = $(this).attr('tit');
    var content = ''
            + '<div class="inner-box">'
            + tit
            + '</div>';
    layer.open({
        type: 1,
        skin: 'layui-layer-rim', //加上边框
        title: '短信内容',
        closeBtn: 0, //不显示关闭按钮
        shadeClose: true, //开启遮罩关闭
        area: ['432px', 'auto'], //宽高
        content: content
    });
});

/*
 * 点击查看优惠券详情
 * @date 2016/4/28
 */
$(".table").delegate("a.details", "click", function () {
    var id = $(this).parent().siblings('#id').text();
    var opuid = $(this).parent().siblings('#opuid').text();
    var index = layer.open({
        type: 2,
        title: false,
        closeBtn: 0, //不显示关闭按钮
        maxmin: false,
        content: '/manualdetails/mdetails',
        success: function (layero, index) {
            fillDetailInfo(layero, id, opuid);
        }
    });
    layer.full(index);
});


/*
 * 获取发放记录详情
 * @date 2016/4/27
 */
function fillDetailInfo(layero, id, opuid) {
    var param = JSON.stringify({"id": id, "opuid": opuid});
    var layerIframe = layero.find('iframe:first-child').contents();
    back(layerIframe);
    var phones = "", coupontype = "", indate = "", price = "", usableline = "", usabletype = "", paymode = "";
    $.ajax({
        type: "POST",
        url: "/couponmanual/gdetail",
        contentType: "application/json",
        dataType: "json",
        data: param,
        success: function (data) {
            if (data.status == 0) {
                for (var i in data.detail.phone) {
                    phones += data.detail.phone[i] + ";";
                }
                layerIframe.find('#phone').val(phones);
                layerIframe.find("#cnt").text(data.detail.data.cnt);
                layerIframe.find('#typedesc').text(data.detail.typedesc);
                if (data.detail.sendmsg == "1") {
                    layerIframe.find("#message").text("是");
                    layerIframe.find("#msg").val(data.detail.msg);
                } else {
                    layerIframe.find("#message").text("否");
                    layerIframe.find('.input-message').hide();
                }
                layerIframe.find("#tag").val(data.detail.remark);
                switch (data.detail.data.type) {
                    case 0:
                        coupontype = "抵用券";
                        price = data.detail.data.sum + '元';
                        break;
                    case 1:
                        coupontype = "折扣券";
                        price = data.detail.data.discount;
                        price = (price % 10 == 0 ? price / 10 : price) + '折';
                        break;
                    case 2:
                        coupontype = "体验券";
                        price = data.detail.data.sum + '元';
                        break;
                }
                layerIframe.find("#coupontype").text(coupontype);
                layerIframe.find("#price").text(price);
                switch (data.detail.data.whenexpire) {
                    case 0:
                        indate = "长期有效";
                        break;
                    case 1:
                        indate = /*data.detail.data.enable_time + " ~ " + */data.detail.data.expire_time;//绝对过期时间
                        break;
                    case 2:
                        indate = data.detail.data.expire_in + '小时';//相对过期时间
                        break;
                }
                layerIframe.find("#indate").text(indate);

                var busi = data.detail.data.usabletype; //业务
                if (busi == -1) {
                    layerIframe.find("input[type='checkbox']").prop("checked", true);
                } else {
                    var busiArray = new Array(0, 0, 0, 0);
                    for (var i = 3; i >= 0; i--) {
                        var j = parseInt(busi / (Math.pow(2, i)));
                        if (j > 0) {
                            busiArray[i] = 1;
                        }
                        busi %= (Math.pow(2, i));
                        if (busi == 0) {
                            break;
                        }
                    }
                    if (busiArray[0]) {
                        layerIframe.find("#incipin").prop("checked", true);
                    }
                    if (busiArray[1]) {
                        layerIframe.find("#incibao").prop("checked", true);
                    }
                    if (busiArray[2]) {
                        layerIframe.find("#package").prop("checked", true);
                    }
                    if (busiArray[3]) {
                        layerIframe.find("#city").prop("checked", true);
                    }
                }

                if (data.detail.data.usableline[0] == "*") {
                    layerIframe.find("#routeAll").prop('checked', true);
                } else {
                    layerIframe.find(".route-all").hide();
                    for (var i in data.detail.data.usableline) {
                        usableline += "<li>" + data.detail.data.usableline[i].line_name + ";</li>";
                    }
                    layerIframe.find("#partRoute").append(usableline);
                }
                switch (data.detail.data.paymode) {
                    case 1:
                        paymode = "线上支付";
                        break;
                    case 2:
                        paymode = "线下支付";
                        break;
                    case 3:
                        paymode = "不限";
                        break;
                }
                layerIframe.find("#payMode").append(paymode);
                var uselimit = !data.detail.data.sum_low_limit || data.detail.data.sum_low_limit < 0 ? "<li>无限制</li>" : "<li>满额使用</li><li>满" + data.detail.data.sum_low_limit + "元可用</li>";
                layerIframe.find("#payNoLimit").append(uselimit);
            } else if (data.status == -501) {//session过期
                window.location.href = '/timeout/index';
            } else {
                bbx_alert_error(data.message);
            }
        },
        error: function (data) {
            bbx_alert_error(data.message);
        }
    });
}

/*
 * 新增手工发放优惠券
 * @date 2016/4/29
 */
function initAddPanel(layero, index, opuid, opname) {
    var layerIframe = layero.find('iframe:first-child').contents();
    var usableline = [];
    getType(layerIframe.find('#type'));
    getStartCity(layerIframe.find("#startCities"), layerIframe.find("#endCities"), layerIframe);
    addLinesModel(layerIframe);
    addSort(layerIframe);
    bussinessMark(layerIframe);
    back(layerIframe);
    checkInputPhone(layerIframe.find("#phones"));
    layerIframe.find("#save").on("click", function () {
        layer.confirm("是否确认发放？", {btn: ['确认', '取消']}, function () {
            layer.closeAll('dialog');

            var phones = decodePhone(layerIframe.find("#phones").val().split(';'));
            if (!checkParam(layerIframe, phones)) {
                layer.msg('请重新填写选项!', {icon: 2, time: 1000/*1秒后自动关闭*/});
                return;
            }

            var usabletype = 0;
            if (layerIframe.find("#busAll").prop("checked")) {
                usabletype = -1;
            } else {
                layerIframe.find("#usabletype input:checked").each(function () {
                    usabletype += parseInt($(this).attr('val'));
                });
            }
            var params = {
                "opuid": opuid,
                "opname": opname,
                "phones": '',
                "type": parseInt(layerIframe.find("#type option:selected").val()),
                "typedesc": layerIframe.find("#type option:selected").text(),
                "remark": layerIframe.find("#tag").val(),
                "sendmsg": parseInt(layerIframe.find("#sendmsg label input:checked").attr('val')),
                "msg": layerIframe.find("#msg").val(),
                "coupontype": parseInt(layerIframe.find("#coupontype option:selected").val()),
                "sum": Number(layerIframe.find("#sum").val()),
                "discount": layerIframe.find("#discount").val().length == 1 ? Number(layerIframe.find("#discount").val()) * 10 : Number(layerIframe.find("#discount").val()),
                "whenexpire": parseInt(layerIframe.find("#whenexpire option:selected").val()),
                "expire_in": Number(layerIframe.find("#expire_in").val()),
                "enable_time": /*layerIframe.find("#enable_time").val()*/'',
                "expire_time": layerIframe.find("#expire_time").val(),
                "usabletype": usabletype,
                "usableline": routeSelect(layerIframe),
                "paymode": parseInt(layerIframe.find("#paymode input:checked").attr('val')),
                "cnt": Number(layerIframe.find("#cnt").val()),
                "sum_low_limit": Number(layerIframe.find("#usesum").val() ? layerIframe.find("#usesum").val() : -1)
            };

            var layerIndex = layer.msg('发放中。。。', {icon: 16, time: 3600000, shade: [0.5, '#fff']});
            grant(layerIndex, params, phones, 0);
        });
    });
}

var all_phones = false;
// 发放优惠券
function grant(layerIndex, params, phones, offset) {
    all_phones = false;
    var p = [];
    var j = 0;
    for (var i = offset; i < offset + 100; i++) {
        if (i == phones.length - 1) {
            all_phones = true;
        } else if (i >= phones.length) {
            break;
        }
        p[j] = phones[i];
        j++;
    }

    params.phones = p;
    var pa = JSON.stringify(params);
    console.log(pa);
    $.ajax({
        type: "POST",
        url: "/coupongrant/submit",
        contentType: "application/json",
        dataType: "json",
        data: pa,
        success: function (data) {
            if (data.status == 0) {
                if (all_phones) {
                    console.log("all_phones");
                    layer.close(layerIndex); //关闭加载层
                    layer.msg('发放成功！', {icon: 1, time: 1000}, function () {
                        all_phones = false;
                        is_incity = -1;
                        layer.closeAll();
                        list();
                    });
                } else {
                    grant(layerIndex, params, phones, offset + 100);
                }
            } else if (data.status == -501) {//session过期
                layer.close(layerIndex); //关闭加载层
                window.location.href = '/timeout/index';
            } else {
                layer.close(layerIndex); //关闭加载层
                bbx_alert_error(data.message);
            }
        },
        error: function () {
            layer.close(layerIndex); //关闭加载层
            bbx_alert_error('出错啦~');
        }
    });
}

// 点击手工发放优惠券
$('#grant-btn').click(function () {
    var opuid = $("#user", parent.document).attr('tit');
    var opname = $("#user", parent.document).text();
    var index = layer.open({
        type: 2,
        title: false,
        closeBtn: 0, //不显示关闭按钮
        maxmin: false,
        content: '/coupongrant/cgrant',
        success: function (layero, index) {
            initAddPanel(layero, index, opuid, opname);
        }
    });
    layer.full(index);
});

// 点击导出报表
$('#export').click(function () {
    var param = JSON.stringify({
        'starttime': $('#starttime').val(),
        'endtime': $('#endtime').val(),
        'type': Number($('#type').val()),
        'phone': $('#phone').val(),
        'opname': $('#opuser').val()
    });
    console.log(param);

    var layerIndex = layer.msg('数据生成中，请稍后。。。', {icon: 16, time: 3600000});

    $.ajax({
        type: "POST",
        url: "/couponmanual/export",
        contentType: "application/json",
        dataType: "json",
        data: param,
        success: function (data) {
            layer.close(layerIndex); //关闭加载层
            if (data.status == 0) {
                console.log(data);
                location = '/' + data.path;
            } else if (data.status == -501) {//session过期
                window.location.href = '/timeout/index';
            } else {
                bbx_alert_error(data.message);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            layer.close(layerIndex); //关闭加载层
            console.log(XMLHttpRequest);
            console.log(textStatus);
            console.log(errorThrown);
            bbx_alert_error("出错啦~");
        }
    });
});

// 点击添加分类
function addSort(elem) {
    var sortcontent = ''
            + '<div class="inner-box">'
            + '<div class="form-group">'
            + '分类:'
            + '<input class="form-control" id="sorted-inpput" style="width:233px;" type="text">'
            + '</div>'
            + '<div class="bot-button">'
            + '<input class="btn btn-lg-blue" id="submit"  type="button" value="确定">'
            + '&emsp;'
            + '<input class="btn btn-lg-blue" id="cancel" type="button" value="取消">'
            + '</div>'
            + '</div>';

    // 添加分类
    elem.on('click', '.sorted-add', function () {
        var index = layer.open({
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: ['auto', 'auto'], //宽高
            content: sortcontent,
            success: function (layero, index) {
                addSorted(layero, index, elem);
            }
        });
    });
}

// 添加分类
function addSorted(layero, index, elem) {
    layero.find('#submit').click(function () {
        if (layero.find('#sorted-inpput').val() == "") {
            bbx_alert_error("输入分类为空!添加失败");
            layer.close(index);
            return;
        }
        var param = JSON.stringify({"description": layero.find('#sorted-inpput').val()});
        $.ajax({
            type: "POST",
            url: "/coupongrant/addgranttype",
            contentType: "application/json",
            dataType: "json",
            data: param,
            success: function (data) {
                if (data.status == 0) {
                    layer.msg('添加成功！', {icon: 1, time: 1000}, function () {
                        getType(elem.find('#type'));
                        layer.close(index);
                    });
                } else if (data.status == -501) {//session过期
                    window.location.href = '/timeout/index';
                } else {
                    bbx_alert_error(data.message);
                }
            },
            error: function () {
                bbx_alert_error("出错啦~");
            }
        });
    });
    layero.find("#cancel").on("click", function () {
        layer.close(index);
    });
}

//检查参数
function checkParam(elem, phones) {
    var rightParam = true;
    var i = 0;
    if (phones.length > 10000) {
        elem.find("#phonesmark").text('最多输入10000个手机号!');
        rightParam = false;
    } else {
        for (; i < phones.length; i++) {
            if (phones[i].length != 11 || phones[i].replace(/^[1-9]\d*$/, '')) {
                break;
            }
        }
        if (!phones.length || i < phones.length) {
            elem.find("#phonesmark").text('请填写正确的手机号!');
            rightParam = false;
        } else {
            elem.find("#phonesmark").text('');
        }
    }

    elem.find("#cnt").val() ? elem.find("#cntmark").text('') : (elem.find("#cntmark").text('请填写!'), rightParam = false);
    typeof (elem.find("#type option:selected").val()) !== 'undefined' ? elem.find("#typemark").text('') : (elem.find("#typemark").text('请添加分类!'), rightParam = false);
    if (elem.find("#messageYes").attr("checked")) {
        if (elem.find("#msg").val()) {
            if (elem.find("#msg").val().length > 70) {
                elem.find("#magremark").addClass('mandatory');
                rightParam = false;
            }
            elem.find("#msgmark").text('');
        } else {
            elem.find("#msgmark").text('请填写!');
            rightParam = false;
        }
    }
    if (elem.find("#tag").val().length > 15) {
        elem.find("#tagmark").addClass('mandatory');
        rightParam = false;
    }
    switch (elem.find("#coupontype option:selected").val()) {
        case "0":
        case "2":
            elem.find("#sum").val() ? elem.find("#summark").text('') : (elem.find("#summark").text('请填写!'), rightParam = false);
            break;
        case "1":
            elem.find("#discount").val() ? elem.find("#discountmark").text('') : (elem.find("#discountmark").text('请填写!'), rightParam = false);
            break;
    }
    switch (elem.find("#whenexpire option:selected").val()) {
        case "2":
            elem.find("#expire_in").val() ? elem.find("#expire_inmark").text('') : (elem.find("#expire_inmark").text('请填写!'), rightParam = false);
            break;
        case "1":
            /*elem.find("#enable_time").val() && */elem.find("#expire_time").val() ? elem.find("#expire_timemark").text('') : (elem.find("#expire_timemark").text('请填写！'), rightParam = false);
            break;
    }
    var allBusinessNotChecked = true;
    elem.find("#usabletype input").each(function () {
        if ($(this).prop("checked")) {
            allBusinessNotChecked = false;
        }
    });
    allBusinessNotChecked ? (elem.find("#usabletypemark").text('请选择业务类型！'), rightParam = false) : elem.find("#usabletypemark").text('');
    if (elem.find("#routePart").attr("checked")) {
        var allRouteRight = true;
        elem.find('.route-part-control .line-model').each(function () {
            if (!$(this).find('input:first-child').attr('data') || !$(this).find('input:nth-child(2)').attr('data')) {
                allRouteRight = false;
            }
        });
        allRouteRight ? elem.find("#routePartmark").text('') : (elem.find("#routePartmark").text('请选择线路！'), rightParam = false);
    }
    switch (elem.find("#limitSelect option:selected").val()) {
        case "0":
            elem.find("#usesum").val() ? elem.find("#usesummark").text('') : (elem.find("#usesummark").text('请填写!'), rightParam = false);
            break;
    }
    return rightParam;
}

// 设置手机号空格转分号
function checkInputPhone(phone) {
    phone.on('keyup', function () {
//        var con = $(this).val().toString();
//        var len = con.length;
//        var endC = con.charAt(len - 1);
//        if (endC == ' ') {
//            con = con.replace(' ', ';');
//            $(this).val(con);
//            return;
//        }
//
//        var reg = /^[0-9]+$/;
//        if (!reg.test(endC)) {
//            con = con.replace(endC, '');
//            $(this).val(con);
//        }
//        var v = $(this).val();
//        console.log(v);
        var v = $(this).val().replace(/\s/g, ';');
        v = v.replace(/[^;0-9]/g, '');
        $(this).val(v);
    });
}

// 把手机号码转成数组
function decodePhone(phoneElem) {
    var phones = [], i = 0;
    for (i in phoneElem) {
        if (phoneElem[i] != "") {
            var j = 0;
            for (; j < phones.length; j++) {
                if (phoneElem[i] == phones[j]) {
                    break;
                }
            }
            if (j == phones.length) {
                phones.push(phoneElem[i]);
            }
        }
    }
    return phones;
}